<template>
  <a-card :bordered="false">
    <a-row :gutter="24">
      <a-col :md="6" :sm="24">
        <a-card hoverable style="height:600px;overflow-y:auto">
          <a-spin :spinning="loadingPer">
            <a-button size="small" type="primary" @click="add">在此菜单下新增</a-button>
            <a-popconfirm title="确定删除?" okText="确定" cancelText="取消" @confirm="del">
              <a-button style="margin-left:5px" size="small" type="danger">删除当前菜单</a-button>
            </a-popconfirm>
            <a-tree :showLine="true" @expand="onExpand" :expandedKeys="expandedKeys" :autoExpandParent="autoExpandParent" v-model="checkedKeys" @select="onSelect" :selectedKeys="selectedMenuKeys" :treeData="treeData" :replaceFields="replaceFields"></a-tree>
          </a-spin>
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <!-- <div class="table-page-search-wrapper" style="margin-bottom:16px">
          <a-row style="margin-bottom:16px">
            <a-col :md="8" :sm="24">
              <a-input-search @search="search" enterButton="查询" />
            </a-col>
          </a-row>
          <a-row>
            <a-button type="primary" class="actionButton" @click="add">添加</a-button>
            <a-popconfirm title="确定删除?" okText="确定" cancelText="取消" @confirm="del">
              <a-button type="primary" class="actionButton">删除</a-button>
            </a-popconfirm>
          </a-row>
        </div>-->
        <div style="text-align:center">
          <a-row :gutter="24">
            <a-col :md="12" :sm="24">
              <a-spin :spinning="spinning" tip="获取数据中..." style="width:400px">
                <div class="spin-content">
                  <a-form :form="form">
                    <a-form-item v-bind="formItemLayout" label="菜单名称">
                      <a-input v-decorator="['MenuName', { rules: [{ required: true, message: '请填写菜单名称!' }] }]" />
                    </a-form-item>
                    <a-form-item v-bind="formItemLayout" label="菜单URL">
                      <a-input v-decorator="['Linkurl', { rules: [{ required: true, message: '请填写菜单名称!' }] }]" />
                    </a-form-item>
                    <a-form-item v-bind="formItemLayout" label="菜单文件地址">
                      <a-input v-decorator="['Component', { rules: [{ required: true, message: '请填写菜单名称!' }] }]">
                        <a-tooltip slot="suffix" :title="tips"> <a-icon type="info-circle" style="color: rgba(0,0,0,.45)" /> </a-tooltip
                      ></a-input>
                    </a-form-item>
                    <a-form-item v-bind="formItemLayout" label="序号">
                      <a-input v-decorator="['Sortnum']" />
                    </a-form-item>
                    <a-form-item v-bind="formItemLayout" label="图标">
                      <a-input-search v-decorator="['iconUrl']" @search="openIcon">
                        <a-button slot="enterButton" type="primary" icon="folder-open"></a-button>
                      </a-input-search>
                    </a-form-item>
                    <a-form-item v-bind="formItemLayout" label="是否显示">
                      <a-switch v-decorator="['IsVisible', { valuePropName: 'checked' }]" checkedChildren="是" unCheckedChildren="否" />
                    </a-form-item>
                    <a-form-item v-bind="formItemLayout1" style="text-align:center;margin-bottom:0">
                      <a-button type="primary" @click="ok">确定</a-button>
                    </a-form-item>
                  </a-form>
                </div>
              </a-spin>
            </a-col>
          </a-row>
        </div>

        <!-- <a-pagination size="small" showQuickJumper :defaultCurrent="2" :total="500" @change="onChange" /> -->
      </a-col>
    </a-row>
    <a-modal title="新增菜单" :visible="visibleAdd" @cancel="handleCancelAdd" :footer="null">
      <div class="waterArea" style="background-color:#fff">
        <a-form :form="formadd">
          <a-form-item v-bind="formItemLayout" label="父菜单名称">
            <a-input v-model="this.parentName" disabled />
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="菜单名称">
            <a-input v-decorator="['MenuName', { rules: [{ required: true, message: '请填写菜单名称!' }] }]" />
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="菜单URL">
            <a-input v-decorator="['Linkurl', { rules: [{ required: true, message: '请填写菜单名称!' }] }]" />
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="菜单文件地址">
            <a-input v-decorator="['Component', { rules: [{ required: true, message: '请填写菜单名称!' }] }]">
              <a-tooltip slot="suffix" :title="tips"> <a-icon type="info-circle" style="color: rgba(0,0,0,.45)" /> </a-tooltip>
            </a-input>
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="序号">
            <a-input v-decorator="['Sortnum']" />
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="图标">
            <a-input-search v-decorator="['iconUrl']" @search="openIcon">
              <a-button slot="enterButton" type="primary" icon="folder-open"></a-button>
            </a-input-search>
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="是否显示">
            <a-switch v-decorator="['IsVisible', { valuePropName: 'checked' }]" checkedChildren="是" unCheckedChildren="否" />
          </a-form-item>
          <a-form-item v-bind="formItemLayout1" style="text-align:center;margin-bottom:0">
            <a-button type="primary" @click="save">保存</a-button>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <a-modal :width="1000" title="图标库" :visible="visible" :centered="true" @cancel="handleCancel" @ok="handleSubmit">
      <icon-selector @change="changeIcon" />
    </a-modal>
  </a-card>
</template>

<script>
import { getMenuList, updateMenu, getMenuByID, appendMenu, deleteMenu } from '@/api/menu'
import IconSelector from '@/components/IconSelector'
export default {
  components: {
    'icon-selector': IconSelector
  },
  data() {
    return {
      tips: '若三层菜单，最顶部菜单文件地址设置RouteView1,二层则为RouteView2。若两层菜单，最顶部菜单文件地址设置RouteView2',
      action: 'add',
      title: '',
      titlePer: '',
      tableCardLoad: false,
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedMenuKeys: [],
      treeData: [],
      replaceFields: {
        key: 'id',
        title: 'name'
      },
      spinning: false,
      data: [],
      queryParam: {},
      pagination: {
        onChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        current: 1,
        total: 0,
        showQuickJumper: true,
        size: 'small',
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        position: 'top'
      },
      // 表头
      columns: [
        {
          title: '菜单名称',
          dataIndex: 'RoleName',
          key: 'RoleName',
          align: 'center'
        },
        {
          title: '图标',
          dataIndex: 'Sortnum',
          key: 'Sortnum',
          align: 'center'
        },
        {
          title: '显示',
          dataIndex: 'Remark',
          key: 'Remark',
          align: 'center'
        },
        {
          title: '排序',
          dataIndex: 'Remark',
          key: 'Remark',
          align: 'center'
        },
        {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      selectedRowKeys: [],
      visible: false,
      visibleAdd: false,
      loading: false,
      loadingPer: false,
      form: this.$form.createForm(this),
      formadd: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 0 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        }
      },
      currentId: null,
      selectedRoleId: null,
      parentName: null
    }
  },
  created() {
    getMenuList().then(res => {
      this.treeData = JSON.parse(res)
    })
  },
  methods: {
    initTreeData() {
      this.loadingPer = true
      getMenuList()
        .then(res => {
          this.treeData = JSON.parse(res)
        })
        .finally(() => {
          this.loadingPer = false
        })
    },
    ok() {
      const {
        form: { validateFields }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.spinning = true
          setTimeout(() => {
            const value = {
              ...values,
              ID: this.currentId
            }
            updateMenu(value)
              .then(res => {
                this.currentId = null
                this.spinning = false
              })
              .then(() => {
                this.initTreeData()
              })
          }, 1000)
        } else {
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    handleCancelAdd() {
      this.visibleAdd = false
    },
    search(data) {
      var _this = this
      _this.spinning = true
      Object.assign(_this.queryParam, data)
      // _this.queryParam = Object.assign({}, data)
      _this.initData(_this.queryParam)
    },
    changeIcon(data) {
      ;(this.action == 'update' && this.form.setFieldsValue({ iconUrl: data })) || this.formadd.setFieldsValue({ iconUrl: data })
    },
    openIcon() {
      this.visible = true
    },
    handleSubmit() {
      this.visible = false
    },
    add() {
      // this.title = '添加角色'
      this.action = 'add'
      this.visibleAdd = true
      this.formadd.resetFields()
    },
    del() {
      this.spinning = true
      deleteMenu({ id: this.currentId })
        .then(res => {
          this.initTreeData()
        })
        .finally(() => {
          this.spinning = false
        })
    },
    save() {
      const {
        formadd: { validateFields }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.loading = true
          setTimeout(() => {
            const value = {
              ...values,
              ParentID: this.currentId || 0
            }
            appendMenu(value)
              .then(res => {
                this.initTreeData()
              })
              .finally(() => {
                this.visibleAdd = false
              })
          }, 1000)
        } else {
        }
      })
    },
    pageOnChange(index, pageSize) {
      this.tableCardLoad = true
      Object.assign(this.pagination, {
        current: index,
        pageSize,
        index
      })
      Object.assign(this.queryParam, {
        pageSize,
        index
      })
      this.initData(this.queryParam)
    },
    onSelect(selectedKeys, e) {
      // this.ParentId = e.selectedNodes[0].data.props.name
      // this.form.setFieldsValue({ ParentName: this.ParentName })
      this.action = 'update'
      console.log(e.selectedNodes)
      this.selectedMenuKeys = selectedKeys
      console.log(this.selectedMenuKeys)
      if (selectedKeys.length == 0) {
        this.currentId = 0
        this.parentName = null
      }
      this.spinning = true
      getMenuByID({ id: selectedKeys[0] })
        .then(res => {
          this.data = res
          this.currentId = res.ID
          this.form.setFieldsValue({ MenuName: res.MenuName })
          this.form.setFieldsValue({ Linkurl: res.Linkurl })
          this.form.setFieldsValue({ Component: res.Component })
          this.form.setFieldsValue({ Sortnum: res.Sortnum })
          this.form.setFieldsValue({ IsVisible: res.IsVisible })
          this.form.setFieldsValue({ iconUrl: res.iconUrl })
          this.parentName = res.MenuName
        })
        .finally(() => {
          this.spinning = false
        })
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    setRow(record) {
      return {
        on: {
          // 事件
          click: event => {
            this.loadingPer = true
            this.selectedRoleId = record.ID
            getMenuButtonsByRoleID({ roleId: record.ID })
              .then(res => {
                this.checkedKeys = res.map(a => {
                  return a.MenuID
                })
              })
              .finally(() => {
                this.loadingPer = false
              })
          }
        }
      }
    },
    setRowClassName(record, idx) {
      return record.ID === this.selectedRoleId ? 'bg-row' : ''
    }
  }
}
</script>
<style lang="less"></style>
<style lang="less" scoped>
.actionButton {
  margin-left: 10px;
}
</style>
